<template>
  <tl-sub-page render="el-drawer" ref="drawerRef" :visible.sync="visible" :with-header="false" :modal-append-to-body="true" :close-on-press-escape="false" :append-to-body="true" class="tl-drawer" :size="'95%'" @open="open" @close="close" :destroy-on-close="true">
    <transition name="change-sub-page">
      <keep-alive :max="5">
        <component :is="subPage" ref="subPage" v-bind="otherProps" render="div" @hook:activated="changeActivatedPage" @hook:mounted="pageCreated" :visible.sync="visible" @close="visible = false"></component>
      </keep-alive>
    </transition>
  </tl-sub-page>
</template>

<script>
/** 工具 */
import { validateNull } from '@tapui/utils/validate'
import { mapGetters } from 'vuex'
export default {
  name: 'dynamicSubPage',
  data() {
    return {
      visible: false,
      title: '动态加载页',
      subPage: 'div',
      id: '',
      // 其余绑定的参数
      otherProps: {},
      // sourceType对应的路径
      sourceTypeMap: {
        ItrTechnicalService: 'itr/itrTechnicalService/edit',
        ItrUntechnicalService: 'itr/itrUntechnicalService/fullEdit',
        ItrGeneralProblem: 'itr/itrGeneralProblem/fullEdit',
        ItrProblemUpgrade: 'itr/itrProblemUpgrade/fullEdit',
        ItrTask: 'itr/itrTask/fullEdit',
        ItrProductParameter: 'itr/itrProductParameter/edit',
        // ItrRelationDept: 'itr/itrUntechnicalService/fullEdit'
        ItrRelationDept: 'itr/itrRelationDept/approvalEdit'
      }
    }
  },
  computed: {
    ...mapGetters(['isOpenDynamicSubPage', 'dynamicSubPageParams'])
  },
  watch: {
    isOpenDynamicSubPage(newVal, oldVal) {
      if (newVal && !oldVal) {
        this.changeSubPage(this.dynamicSubPageParams)
      }
    }
  },
  methods: {
    changeSubPage({ sourceType, sourceId, otherProps }) {
      if (validateNull(sourceType) || validateNull(sourceId)) {
        return
      }
      this.id = sourceId
      if (!this.sourceTypeMap[sourceType]) {
        console.error('未配置单据对应页面')
        return
      }
      if (Object.prototype.toString.call(otherProps) !== '[object Object]') {
        console.error('其余绑定参数必须通过对象传入')
        return
      }
      this.otherProps = otherProps
      this.visible = true
      const page = () => import('@/views/' + this.sourceTypeMap[sourceType])
      this.subPage = page
      this.$store.dispatch('changeDynamicSubPage', false)
    },
    pageCreated() {
      this.$refs.subPage.id = this.id
      this.$refs.subPage.isAdd = false
      this.$refs.subPage.visible = true
      this.$refs.subPage.disableEditSubmit = true
      this.$refs.subPage.open()
    },
    /** 从缓存中切换时 */
    changeActivatedPage() {
      if (this.id === this.$refs.subPage.id) {
        return
      }
      this.$refs.subPage.id = this.id
      this.$refs.subPage.open()
    },
    open() {},
    close() {}
  }
}
</script>

<style lang="scss" scoped>
.change-sub-page-enter-active {
  transition: all 0.5s;
}
.change-sub-page-enter {
  opacity: 0;
  transform: translateX(50px);
}
</style>
